﻿using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Publicuse.Entity;
using Publicuse.Util;

namespace Publicuse.DBCore.Mongodb
{
    public sealed class MongodbInstance
    {
        private string server;

        private string dbname;

        private int port;

        private string uname;

        private string password;

        private static object locker = new object();

        private static MongodbInstance mongodbSqlInstance = null;

        private IMongoDatabase database = null;

        private string constr { get; set; }

        static MongodbInstance()
        {
            mongodbSqlInstance = new MongodbInstance();
        }

        public static MongodbInstance GetInstance
        {
            get { return mongodbSqlInstance; }
        }

        /// <summary>
        /// 数据库实例字段初始化
        /// </summary>
        /// <param name="constr"></param>
        public void Init(string constr)
        {
            if (string.IsNullOrEmpty(constr))
                return;

            var cstr = constr.Split(',');
            this.server = constr.Split(',')[0];
            this.dbname = constr.Split(',')[1];
            this.port = Convert.ToInt32(constr.Split(',')[2].ToString());
            if (cstr.Length > 3)
            {
                this.uname = constr.Split(',')[3];
                this.password = constr.Split(',')[4];
            }
            if (string.IsNullOrEmpty(this.uname) && string.IsNullOrEmpty(this.password))
            {
                constr = string.Format($"mongodb://{server}:{port}");
            }
            else
            {
                constr = string.Format($"mongodb://{uname}:{password}@{server}:{port}/{dbname}");
            }
            this.constr = constr;
            var mongoClient = new MongoClient(constr);
            this.database = mongoClient.GetDatabase(dbname);
        }

        /// <summary>
        /// 获取要操作的表的实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tbname"></param>
        /// <param name="action"></param>
        /// <param name="msg"></param>
        public void GetTableInstance<T>(string tbname,Action<IMongoCollection<T>> action, out string msg)
        {
            msg = string.Empty;
            try
            {
                var client = this.database.GetCollection<T>(tbname);
                action.Invoke(client);
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                //LogUtil.GetInstance.WriteLogOld("连接Mongodb失败", this.constr+"|"+ex.Message, true);
            }
        }

        /// <summary>
        /// 删除表
        /// </summary>
        /// <param name="tbname"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool DeleteTable(string tbname,out string msg)
        {
            msg = string.Empty;
            try
            {
                this.database.DropCollection(tbname);
                return true;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                //LogUtil.GetInstance.WriteLogOld("连接Mongodb失败", this.constr + "|" + ex.Message, true);
                return false;
            }
        }

        /// <summary>
        /// 重置表名
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="oldname"></param>
        /// <param name="newname"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool ClearTable<T>(string oldname, string newname,out string msg)
        {
            msg = string.Empty;
            try
            {
                this.database.RenameCollection(oldname, newname);
                return true;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
               // LogUtil.GetInstance.WriteLogOld("连接Mongodb失败", this.constr + "|" + ex.Message, true);
                return false;
            }
        }

        /// <summary>
        /// 插入一条数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tbname"></param>
        /// <param name="t"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool Add<T>(string tbname, T t, out string msg)
        {
            msg = string.Empty;
            try
            {
                this.database.GetCollection<T>(tbname).InsertOne(t);
                return true;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                //LogUtil.GetInstance.WriteLogOld("连接Mongodb失败", this.constr + "|" + ex.Message, true);
                return false;
            }
        }

        /// <summary>
        /// 异步插入一条数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tbname"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        public async Task<AsyncModel<T>> AddAsync<T>(string tbname, T t)
        {
            AsyncModel<T> result = new AsyncModel<T>();
            try
            {
                await this.database.GetCollection<T>(tbname).InsertOneAsync(t);
                return result;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                //LogUtil.GetInstance.WriteLogOld("连接Mongodb失败", this.constr + "|" + ex.Message, true);
                return result;
            }
        }

        /// <summary>
        /// 批量插入
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tbname"></param>
        /// <param name="t"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool InsertMany<T>(string tbname, List<T> t, out string msg)
        {
            msg = string.Empty;
            try
            {
                this.database.GetCollection<T>(tbname).InsertMany(t);
                return true;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                //LogUtil.GetInstance.WriteLogOld("连接Mongodb失败", this.constr + "|" + ex.Message, true);
                return false;
            }
        }

        /// <summary>
        /// 异步批量插入
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tbname"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        public async Task<AsyncModel<T>> InsertManyAsync<T>(string tbname, List<T> t)
        {
            AsyncModel<T> result = new AsyncModel<T>();
            try
            {
                await this.database.GetCollection<T>(tbname).InsertManyAsync(t);
                return result;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                //LogUtil.GetInstance.WriteLogOld("连接Mongodb失败", this.constr + "|" + ex.Message, true);
                return result;
            }
        }

        /// <summary>
        /// 修改一条数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tbname"></param>
        /// <param name="t"></param>
        /// <param name="id"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool Update<T>(string tbname, T t, string id, out string msg)
        {
            msg = string.Empty;
            try
            {
                var client = this.database.GetCollection<T>(tbname);
                //修改条件
                FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", new ObjectId(id));
                //要修改的字段
                var list = new List<UpdateDefinition<T>>();
                foreach (var item in t.GetType().GetProperties())
                {
                    if (item.Name.ToLower() == "id") continue;
                    list.Add(Builders<T>.Update.Set(item.Name, item.GetValue(t)));
                }
                var updatefilter = Builders<T>.Update.Combine(list);
                client.UpdateOne(filter, updatefilter);
                return true;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                //LogUtil.GetInstance.WriteLogOld("连接Mongodb失败", this.constr + "|" + ex.Message, true);
                return false;
            }
        }

        /// <summary>
        /// 异步修改一条数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tbname"></param>
        /// <param name="t"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<AsyncModel<T>> UpdateAsync<T>(string tbname, T t, string id)
        {
            AsyncModel<T> result = new AsyncModel<T>();
            try
            {
                var client = this.database.GetCollection<T>(tbname);
                //修改条件
                FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", new ObjectId(id));
                //要修改的字段
                var list = new List<UpdateDefinition<T>>();
                foreach (var item in t.GetType().GetProperties())
                {
                    if (item.Name.ToLower() == "id") continue;
                    list.Add(Builders<T>.Update.Set(item.Name, item.GetValue(t)));
                }
                var updatefilter = Builders<T>.Update.Combine(list);
                result.updateResult= await client.UpdateOneAsync(filter, updatefilter);
                return result;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                //LogUtil.GetInstance.WriteLogOld("连接Mongodb失败", this.constr + "|" + ex.Message, true);
                return result;
            }
        }

        /// <summary>
        /// 批量修改数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tbname"></param>
        /// <param name="dic"></param>
        /// <param name="filter"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool UpdateManay<T>(string tbname, Dictionary<string, string> dic, FilterDefinition<T> filter, out string msg)
        {
            msg = string.Empty;
            try
            {
                var client = this.database.GetCollection<T>(tbname);
                T t = default(T);
                //要修改的字段
                var list = new List<UpdateDefinition<T>>();
                foreach (var item in t.GetType().GetProperties())
                {
                    if (!dic.ContainsKey(item.Name)) continue;
                    var value = dic[item.Name];
                    list.Add(Builders<T>.Update.Set(item.Name, value));
                }
                var updatefilter = Builders<T>.Update.Combine(list);
                client.UpdateMany(filter, updatefilter);
                return true;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                //LogUtil.GetInstance.WriteLogOld("连接Mongodb失败", this.constr + "|" + ex.Message, true);
                return false;
            }
        }

        /// <summary>
        /// 异步批量修改数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tbname"></param>
        /// <param name="dic"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public async Task<AsyncModel<T>> UpdateManayAsync<T>(string tbname, Dictionary<string, string> dic, FilterDefinition<T> filter)
        {
            AsyncModel<T> result = new AsyncModel<T>();
            try
            {
                var client = this.database.GetCollection<T>(tbname);
                T t = default(T);
                //要修改的字段
                var list = new List<UpdateDefinition<T>>();
                foreach (var item in t.GetType().GetProperties())
                {
                    if (!dic.ContainsKey(item.Name)) continue;
                    var value = dic[item.Name];
                    list.Add(Builders<T>.Update.Set(item.Name, value));
                }
                var updatefilter = Builders<T>.Update.Combine(list);
                result.updateResult= await client.UpdateManyAsync(filter, updatefilter);
                return result;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                //LogUtil.GetInstance.WriteLogOld("连接Mongodb失败", this.constr + "|" + ex.Message, true);
                return result;
            }
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tbname"></param>
        /// <param name="id"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool DeleteOne<T>(string tbname, string id, out string msg)
        {
            msg = string.Empty;
            try
            {
                var client = this.database.GetCollection<T>(tbname);
                FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", new ObjectId(id));
                client.DeleteOne(filter);
                return true;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                //LogUtil.GetInstance.WriteLogOld("连接Mongodb失败", this.constr + "|" + ex.Message, true);
                return false;
            }
        }

        /// <summary>
        /// 异步删除一条数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tbname"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<AsyncModel<T>> DeleteOneAsync<T>(string tbname, string id)
        {
            AsyncModel<T> result = new AsyncModel<T>();
            try
            {
                var client = this.database.GetCollection<T>(tbname);
                FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", new ObjectId(id));
                result.deleteResult= await client.DeleteOneAsync(filter);
                return result;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                //LogUtil.GetInstance.WriteLogOld("连接Mongodb失败", this.constr + "|" + ex.Message, true);
                return result;
            }
        }

        /// <summary>
        /// 删除多条数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tbname"></param>
        /// <param name="filter"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool DeleteMany<T>(string tbname, FilterDefinition<T> filter, out string msg)
        {
            msg = string.Empty;
            try
            {
                var client = this.database.GetCollection<T>(tbname);
                client.DeleteMany(filter);
                return true;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                //LogUtil.GetInstance.WriteLogOld("连接Mongodb失败", this.constr + "|" + ex.Message, true);
                return false;
            }
        }

        /// <summary>
        /// 异步删除多条数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tbname"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public async Task<AsyncModel<T>> DeleteManyAsync<T>(string tbname, FilterDefinition<T> filter)
        {
            AsyncModel<T> result = new AsyncModel<T>();
            try
            {
                var client = this.database.GetCollection<T>(tbname);
                result.deleteResult = await client.DeleteManyAsync(filter);
                return result;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                //LogUtil.GetInstance.WriteLogOld("连接Mongodb失败", this.constr + "|" + ex.Message, true);
                return result;
            }
        }

        /// <summary>
        /// 根据条件获取总数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tbname"></param>
        /// <param name="filter"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public long Count<T>(string tbname, FilterDefinition<T> filter, out string msg)
        {
            msg = string.Empty;
            try
            {
                var client = this.database.GetCollection<T>(tbname);
                return client.CountDocuments(filter);
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                //LogUtil.GetInstance.WriteLogOld("连接Mongodb失败", this.constr + "|" + ex.Message, true);
                return 0;
            }
        }

        /// <summary>
        /// 异步根据条件获取总数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tbname"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public async Task<AsyncModel<T>> CountAsync<T>(string tbname, FilterDefinition<T> filter)
        {
            AsyncModel<T> result = new AsyncModel<T>();
            try
            {
                var client = this.database.GetCollection<T>(tbname);
                result.count= await client.CountDocumentsAsync(filter);
                return result;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                //LogUtil.GetInstance.WriteLogOld("连接Mongodb失败", this.constr + "|" + ex.Message, true);
                return result;
            }
        }

        /// <summary>
        /// 根据id查询一条数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tbname"></param>
        /// <param name="id"></param>
        /// <param name="msg"></param>
        /// <param name="field"></param>
        /// <returns></returns>
        public bool FindOne<T>(string tbname, string id, out string msg, string[] field = null)
        {
            msg = string.Empty;
            try
            {
                var client = this.database.GetCollection<T>(tbname);
                FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", new ObjectId(id));
                //不指定查询字段
                if (field == null || field.Length == 0)
                {
                    client.Find(filter).FirstOrDefault<T>();
                    return true;
                }

                //制定查询字段
                var fieldList = new List<ProjectionDefinition<T>>();
                for (int i = 0; i < field.Length; i++)
                {
                    fieldList.Add(Builders<T>.Projection.Include(field[i]));
                }
                var projection = Builders<T>.Projection.Combine(fieldList);
                fieldList?.Clear();
                client.Find(filter).Project<T>(projection).FirstOrDefault<T>();
                return true;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                //LogUtil.GetInstance.WriteLogOld("连接Mongodb失败", this.constr + "|" + ex.Message, true);
                return false;
            }
        }

        /// <summary>
        /// 异步根据id查询一条数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tbname"></param>
        /// <param name="id"></param>
        /// <param name="field"></param>
        /// <returns></returns>
        public async Task<AsyncModel<T>> FindOneAsync<T>(string tbname, string id, string[] field = null)
        {
            AsyncModel<T> result = new AsyncModel<T>();
            try
            {
                var client = this.database.GetCollection<T>(tbname);
                FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", new ObjectId(id));
                //不指定查询字段
                if (field == null || field.Length == 0)
                {
                    result.entity= await client.Find(filter).FirstOrDefaultAsync<T>();
                    return result;
                }

                //制定查询字段
                var fieldList = new List<ProjectionDefinition<T>>();
                for (int i = 0; i < field.Length; i++)
                {
                    fieldList.Add(Builders<T>.Projection.Include(field[i]));
                }
                var projection = Builders<T>.Projection.Combine(fieldList);
                fieldList?.Clear();
                result.entity = await client.Find(filter).Project<T>(projection).FirstOrDefaultAsync<T>();
                return result;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                //LogUtil.GetInstance.WriteLogOld("连接Mongodb失败", this.constr + "|" + ex.Message, true);
                return result;
            }
        }

        /// <summary>
        /// 查询集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tbname"></param>
        /// <param name="msg"></param>
        /// <param name="filter"></param>
        /// <param name="list"></param>
        /// <param name="field"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        public bool GetList<T>(string tbname, out string msg, FilterDefinition<T> filter, out List<T> list, string[] field = null, SortDefinition<T> sort = null)
        {
            msg = string.Empty;
            list = new List<T>();
            try
            {
                var client = this.database.GetCollection<T>(tbname);
                //不指定查询字段
                if (field == null || field.Length == 0)
                {
                    if (sort == null)
                    {
                        list = client.Find(filter).ToList();
                        return true;
                    }

                    //进行排序
                    list = client.Find(filter).Sort(sort).ToList();
                    return true;
                }

                //制定查询字段
                var fieldList = new List<ProjectionDefinition<T>>();
                for (int i = 0; i < field.Length; i++)
                {
                    fieldList.Add(Builders<T>.Projection.Include(field[i]));
                }
                var projection = Builders<T>.Projection.Combine(fieldList);
                fieldList?.Clear();
                if (sort == null)
                {
                    list = client.Find(filter).Project<T>(projection).ToList();
                    return true;
                }
                //排序查询
                list =client.Find(filter).Sort(sort).Project<T>(projection).ToList();
                return true;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                //LogUtil.GetInstance.WriteLogOld("连接Mongodb失败", this.constr + "|" + ex.Message, true);
                return false;
            }
        }

        /// <summary>
        /// 异步查询集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tbname"></param>
        /// <param name="filter"></param>
        /// <param name="field"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        public async Task<AsyncModel<T>> GetListAsync<T>(string tbname, FilterDefinition<T> filter, string[] field = null, SortDefinition<T> sort = null)
        {
            AsyncModel<T> result = new AsyncModel<T>();
            try
            {
                var client = this.database.GetCollection<T>(tbname);
                //不指定查询字段
                if (field == null || field.Length == 0)
                {
                    if (sort == null)
                    {
                        result.list = await client.Find(filter).ToListAsync();
                        return result;
                    }

                    //进行排序
                    result.list = await client.Find(filter).Sort(sort).ToListAsync();
                    return result;
                }

                //制定查询字段
                var fieldList = new List<ProjectionDefinition<T>>();
                for (int i = 0; i < field.Length; i++)
                {
                    fieldList.Add(Builders<T>.Projection.Include(field[i]));
                }
                var projection = Builders<T>.Projection.Combine(fieldList);
                fieldList?.Clear();
                if (sort == null)
                {
                    result.list = await client.Find(filter).Project<T>(projection).ToListAsync();
                    return result;
                }
                //排序查询
                result.list = await client.Find(filter).Sort(sort).Project<T>(projection).ToListAsync();
                return result;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                //LogUtil.GetInstance.WriteLogOld("连接Mongodb失败", this.constr + "|" + ex.Message, true);
                return result;
            }
        }

        /// <summary>
        /// 分页查询集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tbname"></param>
        /// <param name="filter"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="list"></param>
        /// <param name="msg"></param>
        /// <param name="field"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        public bool GetListByPage<T>(string tbname, FilterDefinition<T> filter, int pageIndex, int pageSize, out long count, out List<T> list, out string msg,string[] field = null, SortDefinition<T> sort = null)
        {
            list = new List<T>();
            msg = string.Empty;
            count = 0;
            try
            {
                var client = this.database.GetCollection<T>(tbname);
                count = client.CountDocuments(filter);
                //不指定查询字段
                if (field == null || field.Length == 0)
                {
                    if (sort == null)
                    {
                        list = client.Find(filter).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();
                        return true;
                    }
                    //进行排序
                    list = client.Find(filter).Sort(sort).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();
                    return true;
                }

                //制定查询字段
                var fieldList = new List<ProjectionDefinition<T>>();
                foreach (var item in field)
                {
                    fieldList.Add(Builders<T>.Projection.Include(item));
                }
                var projection = Builders<T>.Projection.Combine(fieldList);
                fieldList?.Clear();
                //不排序
                if (sort == null)
                {
                    list = client.Find(filter).Project<T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();
                    return true;
                }
                //排序查询
                list = client.Find(filter).Sort(sort).Project<T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();
                return true;

            }
            catch (Exception ex)
            {
                msg = ex.Message;
                //LogUtil.GetInstance.WriteLogOld("连接Mongodb失败", this.constr + "|" + ex.Message, true);
                return false;
            }
        }

        /// <summary>
        /// 异步分页查询集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tbname"></param>
        /// <param name="filter"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="field"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        public async Task<AsyncModel<T>> GetListByPageAsync<T>(string tbname,int pageIndex,int pageSize, FilterDefinition<T> filter, SortDefinition<T> sort=null, string[] field=null)
        {
            AsyncModel<T> result = new AsyncModel<T>(pageIndex, pageSize);
            try
            {
                var client = this.database.GetCollection<T>(tbname);
                result.count = client.CountDocuments(filter);
                //不指定查询字段
                if (field == null || field.Length == 0)
                {
                    if (sort == null)
                    {
                        result.list = await client.Find(filter).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync();
                        return result;
                    }
                    //进行排序
                    result.list = await client.Find(filter).Sort(sort).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync();
                    return result;
                }

                //制定查询字段
                var fieldList = new List<ProjectionDefinition<T>>();
                foreach (var item in field)
                {
                    fieldList.Add(Builders<T>.Projection.Include(item));
                }
                var projection = Builders<T>.Projection.Combine(fieldList);
                fieldList?.Clear();

                //不排序
                if (sort == null)
                {
                    result.list = await client.Find(filter).Project<T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync();
                    return result;
                }
                //排序查询
                result.list = await client.Find(filter).Sort(sort).Project<T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync();
                return result;

            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                //LogUtil.GetInstance.WriteLogOld("连接Mongodb失败", this.constr + "|" + ex.Message, true);
                return result;
            }
        }
    }
}
